var mainApp = angular.module("mainApp", ["angular-popups", "scService", "ui.router", "loginApp", "userInfoApp", "myOrderApp", "orderPayApp", "orderPayDetailApp", "orderDetailApp", "chargeStarted", "charging", "appointingApp", "manualCode", "searchApp", "searchResultApp"]);
mainApp.config(function($urlRouterProvider, $stateProvider, $locationProvider) {
    $stateProvider
        .state("index_", {
            url: "/index_",
            templateUrl: "index_.html",
            controller: "indexController"
        })
        .state("orderPay", {
            url: "/orderPay/:orderNo",
            templateUrl: "assets/scripts/app/orderPay/views/orderPay.html"
        })
        .state("paySuccess", {
            url: "/paySuccess/:orderNo",
            templateUrl: "assets/scripts/app/orderPay/views/paySuccess.html"
        })
        .state("payFail", {
            url: "/payFail/:orderNo",
            templateUrl: "assets/scripts/app/orderPay/views/payFail.html"
        })
        .state("orderPayDetail", {
            url: "/orderPayDetail/:orderNo",
            templateUrl: "assets/scripts/app/orderPay/views/orderPayDetail.html"
        })
        .state("orderDetail", {
            url: "/orderDetail/:orderNo",
            templateUrl: "assets/scripts/app/orderPay/views/orderDetail.html"
        })
        .state("login", {
            url: "/login/:code",
            templateUrl: "assets/scripts/app/login/views/login.html"
        })
        .state("userInfo", {
            url: "/userInfo",
            templateUrl: "assets/scripts/app/userInfo/views/userInfo.html"
        })
        .state("myCollect", {
            url: "/myCollect",
            templateUrl: "assets/scripts/app/userInfo/views/myCollect.html"
        })
        .state("operation", {
            url: "/operation",
            templateUrl: "assets/scripts/app/userInfo/views/operation.html"
        })
        .state("myOrder", {
            url: "/myOrder",
            templateUrl: "assets/scripts/app/myOrder/views/myOrder.html"
        })
        .state("myOrder.pending", {
            url: "/pending",
            templateUrl: "assets/scripts/app/myOrder/views/pending.html"
        })
        .state("myOrder.processing", {
            url: "/processing",
            templateUrl: "assets/scripts/app/myOrder/views/processing.html"
        })
        .state("myOrder.over", {
            url: "/over",
            templateUrl: "assets/scripts/app/myOrder/views/over.html"
        })
        .state("evaluation", {
            url: "/evaluation",
            templateUrl: "assets/scripts/app/orderPay/views/evaluation.html"
        })
        .state("notPay", {
            url: "/notPay",
            templateUrl: "assets/scripts/app/login/views/notPay.html"
        })
        // 扫码充电部分
        .state("chargeStarted", {
            url: "/chargeStarted",
            templateUrl: "assets/scripts/app/scanCharging/views/chargeStarted.html",
            controller: "chargeStartedController"
        })
        .state("charging", {
            url: "/charging",
            templateUrl: "assets/scripts/app/scanCharging/views/charging.html",
            controller: "chargingController"
        })
        .state("manualCode", {
            url: "/manualCode",
            templateUrl: "assets/scripts/app/scanCharging/views/manualCode.html",
            controller: "againScanController"
        })
        .state("errorScan", {
            url: "/errorScan",
            template: '<div class="mc-ct"><div class="mc-pic"><img src="assets/images/Icon_error@2x.png" alt=""><p class="fs18 color666 t-b">请扫描充电桩上二维码</p></div></div>'
        })
        .state("elgal", {
            url: "/elgal",
            templateUrl: "assets/legal.html"
        })
        .state("search", {
            url: "/search",
            templateUrl: "assets/scripts/app/search/views/search.html",
            controller: "searchController"
        })
        .state("checkCity", {
            url: "/checkCity",
            templateUrl: "assets/scripts/app/search/views/checkCity.html",
            controller: "checkCityController"
        })
        .state("searchResult", {
            url: "/searchResult",
            templateUrl: "assets/scripts/app/search/views/searchResult.html",
            controller: "searchResultController"
        })
        .state("beAppointing", { //开始预约
            url: "/beAppointing/:chargerId",
            templateUrl: "assets/scripts/app/appointment/views/beAppointing.html",
            controller: "beAppointingController"
        })
        .state("appointing", { //预约中
            url: "/appointing/:appointingId",
            templateUrl: "assets/scripts/app/appointment/views/appointing.html",
            controller: "appointingController"
        })
        .state("station", { //站点
            url: "/station",
            templateUrl: "assets/scripts/app/station/stationList.html"
                // controller:""
        })
        .state("station.pilePosition", {
            url: "/pilePosition",
            templateUrl: "assets/scripts/app/station/pilePosition.html"
        })
        .state("station.stationDetails", {
            url: "/stationDetails",
            templateUrl: "assets/scripts/app/station/stationDetails.html"
        })
        .state("stateDetail", {
            url: "/stateDetail",
            templateUrl: "assets/scripts/app/appointment/views/stateDetail.html",
            controller: "stateDetailController"
        })
})

mainApp.controller('weuiCtrl', function($scope, $rootScope) {
    $rootScope.showLogin = false;
    //confirm类型
    $scope.confirmSet = function(confirm) {
            var defailt_confirm = document.getElementById("defailt_confirm");
            defailt_confirm.style.display = "block";
            $scope.confirm = {
                title: confirm.title,
                content: confirm.content,
                button: confirm.button
            };
        }
        //Toast类型
    $scope.toastSet = function(toast) {
            var defailt_toast = document.getElementById("defailt_toast");
            defailt_toast.style.display = "block";
            $scope.toast = {
                content: toast.content,
                kind: toast.kind
            };
            setTimeout(function() {
                defailt_toast.style.display = "none";
            }, 2000);
        }
        // 退出登录
    $rootScope.showEx = false;
    $scope.setConfirmEx = function() {
            $rootScope.showEx = true;
        }
        // 双按钮confirm 退出确认退出
    $rootScope.showWeird = false;
    $scope.weirdConfirmSet = function(weirdConfirm) {
            $rootScope.showWeird = true;
            $scope.weirdConfirm = weirdConfirm;
        }
        //loading类型
    $scope.loadingToastSet = function(content) {
            var defailt_toast = document.getElementById("loadingToast");
            defailt_toast.style.display = "block";
            $scope.loadingToastContent = {
                content: content
            };
        }
        //隐藏loading
    $scope.loadingToastHide = function() {
        var defailt_toast = document.getElementById("loadingToast");
        defailt_toast.style.display = "none";
    }

});
// 登录控制器
mainApp.controller("loginController", function($scope, $rootScope, $timeout, scCodeService) {
    $scope.phoneNumber;
    $scope.send = "验证";
    $scope.code;
    $scope.codeClick = true;
    $scope.couldClick = true;
    $scope.loginIng = false;
    $scope.isTimer = false; //判断定时器是否触发，是：解除验证手机 ng-keyup=checkCodeValid()
    var openId = "";
    //重发验证码计时器
    $scope.timer = function(wait) {
        var wait = wait;
        if (wait == 0) {
            $scope.send = "重新发送";
            wait = wait;
            $scope.isTimer = false;
            $scope.codeClick = false;
        } else {
            wait--;
            $scope.isTimer = true;
            $scope.codeClick = true;
            $scope.send = wait + "(s)"
            $timeout(function() {
                $scope.timer(wait)
            }, 1000);
        }
    };
    //点击发送验证码按钮
    $scope.sendCode = function() {
        $scope.timer(60);
        if (!(/^1[34578]\d{9}$/.test($scope.phoneNumber))) {

            $scope.toastSet({
                content: "请输入正确手机号"
            })
        } else {
            var postData = {
                "phone": $scope.phoneNumber,
                "merchantCode": htConfig.merchantCode
            }
            scCodeService.sendVerifyCode(postData).then(function(data) {
                var datastr = JSON.stringify(data);
                //alert(datastr);
                if (data.code == "200") {
                    $scope.timer(60);
                    $scope.toastSet({
                        content: "已发送"
                    });
                    $scope.gotCode = true;
                } else if (data.code == "0106004") {
                    $scope.toastSet({
                        content: "1分钟之内只能发送一次"
                    });
                } else {
                    $scope.toastSet({
                        content: data.msg
                    });
                }
            });
        }
    };

    $scope.login = function() {
        var deferred = $q.defer();
        $scope.couldClick = true; //禁点登录   
        $scope.loginIng = true; //loding弹出 
        var postData = {
            "phone": $scope.phoneNumber,
            "verifyCode": $scope.code,
            "source": htConfig.source,
            "merchantCode": htConfig.merchantCode,
            "account": openId
        };
        /*scCodeService.login(postData).then(function(data) {
            $scope.couldClick = false; //取消禁点登录
            var datastr = JSON.stringify(data);
            // alert(datastr);
            if (data.code == "200") {
                deferred.resolve();
            } else if (data.code == "0101011" || data.code == "0101015") {
                $scope.loginIng = false; //关闭loading   
                $scope.toastSet({
                    content: "验证码错误"
                });
            } else if (data.code == "0101302") {
                $scope.loginIng = false; //关闭loading   
                $scope.toastSet({
                    content: "帐号已绑定"
                });
            } else {
                $scope.loginIng = false; //关闭loading   
                $scope.toastSet({
                    content: "登录失败,请稍后重试"
                });
            }
        });*/
        $timeout(function() {
            console.log("登录成功")
        }, 1000);
        return deferred.promise;
    };
    //验证合性改变按钮颜色
    $scope.checkCodeValid = function() {
        $scope.codeClick = (/^\d{11}$/.test($scope.phoneNumber)) ? false : true;
    };
    $scope.checkValid = function() {
        $scope.couldClick = ((/^1[34578]\d{9}$/.test($scope.phoneNumber)) &&
            (/^(\d)+$/.test($scope.code))) ? false : true;
    };
    // 点击登录按钮
    $scope.loginFun = function() {
        if ($scope.gotCode == true) {
            login().then(function() {
                return $rootScope.autoLogin();
            }).then(function() {
                return $rootScope.getUserCard()
            }).then(function() {
                if ($rootScope.state == '0') {
                    $location.path('userInfo')
                } else if ($rootScope.state == '1') {
                    window.location.href = htConfig.hostUrl + "scanCode.html";
                }
            })
        } else {
            $scope.toastSet({
                content: '请先获取验证码'
            })
        }
    };
});

// 首页控制器
mainApp.controller("indexController", function($scope, $rootScope, scCodeService, $stateParams, $q, $timeout, $location) {
    // $rootScope.showLogin = true;
    $scope.keywords = "";
    //获取openId
    $scope.getOpenId = function() {
        console.log('获取openId执行了')
        var deferred = $q.defer();
        var code = $stateParams.code;
        var postData = {
            "source": mainConfig.source,
            "merchantCode": mainConfig.merchantCode,
            "code": code
        };
        localStorage.setItem("openId", "openId");
        $timeout(function() {
            console.log("获取openId结束");
            $scope.openId = "我是openId"
            return deferred.resolve()
        }, 1000);
        /*scCodeService.getOpenId(postData).then(function(data) {
            if (data.data.openid) {
                var openId = data.data.openid;
                var access_token = data.data.access_token;
                localStorage.setItem("openId", openId);
                localStorage.setItem("access_token", access_token);
                return deferred.resolve();
            } else {
                var state = localStorage.getItem("state");
                window.location.href = mainConfig.hostUrl + "enter.html?state=" + state
            }
        });*/
        return deferred.promise;
    };

    // 自动登录

    $rootScope.autoLogin = function() {
        console.log('自动登录执行了' + $scope.openId)
        var deferred = $q.defer();
        // var num = '';
        // for(var i=0;i<8;i++){
        //  num+=parseInt(Math.random()*10);
        // }
        // var openId = num;
        var openId = localStorage.getItem("openId")
        var postData = {
                "source": mainConfig.source,
                "merchantCode": mainConfig.merchantCode,
                "account": openId,
                "jPushRegId": openId
            }
            /*scCodeService.autoLogin(postData).then(function(data) {
                if (data.code == "200") {
                    localStorage.setItem("userId", data.data.userId);
                    localStorage.setItem("token", data.data.token);
                    localStorage.setItem("phone", data.data.phone);
                    return deferred.resolve()
                    // alert("autoLogin is ok"); 

                } else if (data.code == "500") {
                    $scope.toastSet({
                        content: "系统故障"
                    });
                } else if (data.code == "201" || data.code == "0101001") {
                    $scope.showLogin = true;
                } else {
                    $scope.toastSet({
                        content: "登录失败"
                    });
                }
            });*/
        $timeout(function() {
            console.log('自动登录结束')
            deferred.resolve()
        }, 1000);
        return deferred.promise;

    };
    //获取用户卡号
    $rootScope.getUserCard = function() {
        console.log('获取用户卡号执行了')
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            "userId": userId
        };
        $timeout(function() {
            return deferred.resolve()
        }, 1000);
        /*scCodeService.getUserCard(postData).then(function(data) {
            var datastr = JSON.stringify(data);
            // alert(datastr);
            $scope.loginIng = false; //登录成功关闭loading   
            if (data.code == "200") {
                localStorage.setItem("cardNo", data.data[0].cardNo)
                return deferred.resolve()
            }

        });*/
        return deferred.promise;
    };

    // 查询有无未支付订单
    $scope.getPending = function() {
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            userId: userId,
            pageNo: "1",
            status: "0"
        };
        $timeout(function() {
            console.log("查询未支付订单结束")
            deferred.resolve("1234")
        }, 1000);
        /*scCodeService.getOrderList(postData).then(function(data) {
            var datastr = JSON.stringify(data);
            // alert(datastr);
            if (data.code == "200") {
                deferred.resolve(data.data)
            }
        });*/
        return deferred.promise;
    };
    // 获取附近充电站个数
    $scope.getStationsAround = function() {
        var postData = {};
        $scope.stationsNum = 32;
        console.log("获取附近充电站个数")
    };
    // user Click
    $scope.user = function(index) {
        // var login = localStorage.getItem("isLogin");
        // var login =true;
        if (login == true) {
            if (index == 0) {
                $location.path("userInfo")
            } else {
                $location.path("scanCode")
            }
        } else {
            $rootScope.state = index;
            $rootScope.showLogin = true;
        }
    };
    // 搜索
    $scope.search = function() {
        console.log('点了搜索，搜索内容是' + $scope.keywords)
        var postData = {
            "keywords": $scope.keywords
        }
    };
    // 推荐周边
    $scope.recommend = function() {
        console.log("正在推荐")
    };
    //进入首页执行的方法
    $scope.getOpenId().then(function(data) {
        $scope.getStationsAround();
        return $rootScope.autoLogin()
    }).then(function(data) {
        return $rootScope.getUserCard()
    }).then(function() {
        // var isCharging = localStorage.getItem("isOpenCharging");
        var isCharging = "false";
        if (isCharging == "true") {
            // $location.path("/charging");
            console.log("跳转充电页面")
            var deferred = $q.defer();
            deferred.reject();
            return deferred.promise;
        } else {
            return $scope.getPending()
        }
    }).then(function(data) {
        /*if (data.length != 0) {
            $scope.notPayCardNo = data[0].orderNo;
            localStorage.setItem("notPayCardNo", $scope.notPayCardNo)
            $location.path("/notPay")
        } else {
            window.location.href = htConfig.hostUrl + "scanCode.html";
        }*/
        console.log(data);
    })


})

// 渲染模版
mainApp.directive('confirm', function() {
    return {
        restrict: 'EA',
        templateUrl: 'assets/scripts/plugins/weui-angular/default_confirm.html',
        replace: true,
        link: function(scope) {
            scope.confirmHide = function() {
                var defailt_confirm = document.getElementById("defailt_confirm");
                defailt_confirm.style.display = "none";
            }
        }
    }
});
mainApp.directive('toast', function() {
    return {
        restrict: 'EA',
        templateUrl: 'assets/scripts/plugins/weui-angular/default_toast.html',
        replace: true
    }
});
//退出登录弹层指令
mainApp.directive('confirmEx', function($rootScope) {
    return {
        restrict: 'EA',
        templateUrl: 'assets/scripts/plugins/weui-angular/confirmEx.html',
        replace: true,
        link: function(scope) {
            scope.confirmExHide = function() {
                $rootScope.showEx = false;
            };
        }
    }
});
mainApp.directive('weirdConfirm', function($rootScope) {
    return {
        restrict: 'EA',
        templateUrl: 'assets/scripts/plugins/weui-angular/weird_confirm.html',
        replace: true,
        link: function(scope) {
            scope.weirdConfirmHide = function() {
                $rootScope.showWeird = false;
            }
        }
    }
});

// 登录指令
mainApp.directive('login', function($rootScope) {
    return {
        restrict: 'EA',
        templateUrl: 'assets/scripts/plugins/weui-angular/login.html',
        replace: true,
        controller: 'loginController',
        link: function(scope) {
            scope.loginHide = function() {
                $rootScope.showLogin = false;
            };
        }

    }
});
